package com.xgxf.server.controller;

import com.xgxf.server.common.JsonResult;
import com.xgxf.server.pojo.FilesManageQuery;
import com.xgxf.server.service.IFilesmanageService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/filesmanage")
public class FilesManageController {

    @Autowired
    private IFilesmanageService service;

    @ApiOperation("获取列表")
    @GetMapping("/getList")
    public JsonResult getList(FilesManageQuery parameterQuery){
        return service.getList(parameterQuery);
    }

    @ApiOperation("获取列表")
    @GetMapping("/getVinList")
    public JsonResult getVinList(){
        return service.getVinList();
    }

    @GetMapping("/downloadFile")
    public ResponseEntity<InputStreamResource> downloadFile(@RequestParam("filePath") String filePath) throws IOException {
        if(filePath == null || "".equals(filePath)){
            return null;
        }
        try {
            //读取文件
            FileSystemResource file = new FileSystemResource(filePath);
            //设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");

            ResponseEntity<InputStreamResource> responseEntity = ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentLength(file.contentLength())
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new InputStreamResource(file.getInputStream()));
            System.out.println(responseEntity);
            return responseEntity;

        }catch (Exception e){
            e.printStackTrace();
            log.info("下载文件失败,文件路径{}",filePath);
            return ResponseEntity.status(500).build();
        }
    }

}
